package com.base.taskreports.reports.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.taskreports.common.utlis.DateUtil;
import com.base.taskreports.common.utlis.ThresholdUtlis;
import com.base.taskreports.reports.dao.master.TIndicatorsDao;
import com.base.taskreports.reports.entiyt.master.ExcelBean;
import com.base.taskreports.reports.entiyt.master.TIndicatorsEntity;
import com.base.taskreports.reports.entiyt.master.TThresholdEntity;
import com.base.taskreports.reports.service.TIndicatorsService;
import com.base.taskreports.reports.service.TThresholdService;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张玉涛
 * @since 2021-11-09
 */
@DS("master")
@Service("tIndicatorsService")
public class TIndicatorsServiceImpl extends ServiceImpl<TIndicatorsDao, TIndicatorsEntity> implements TIndicatorsService {

	@Autowired
	private TIndicatorsDao tIndicatorsDao;
	
	@Autowired
	private TThresholdService tThresholdService;

	/**
	 * 将查询到的值插入指标表
	 * @param indicatorCode
	 * @param strDate
	 * @param list
	 */
	@Override
	public void saveIndicators(String indicatorCode,String strDate,List<TIndicatorsEntity> list){
		// 删除之前指标表中的值
		UpdateWrapper<TIndicatorsEntity> updateWrapper = new UpdateWrapper<>() ;
		updateWrapper.eq("indicator_code",indicatorCode) ;
		updateWrapper.eq("indicator_date", strDate ) ;
		this.remove(updateWrapper) ;

		// 将值插入指标表
		this.saveBatch(list) ;
	}
	
	
	@Override
	public void saveTIndicators(TIndicatorsEntity tIndicatorsEntity) {
		//先删除当天的指标
		this.deleteTIndicatorsEntity(tIndicatorsEntity);
		//在增加当天的指标
		TIndicatorsEntity setTIndicatorsEntity = this.setTIndicatorsEntity(tIndicatorsEntity);
		baseMapper.insert(setTIndicatorsEntity);
	}
	

	//查询工具 -- 前8天的总和指标值
    public BigDecimal selectIndexEachDay(String startDate,String endDate,String code){
		QueryWrapper<TIndicatorsEntity> queryWrapper = new QueryWrapper<TIndicatorsEntity>();
		queryWrapper.select(" COALESCE (sum(indicator_value),0) as sumIndicatorValue");
		queryWrapper.eq("indicator_code", code);
		queryWrapper.ge("indicator_date", startDate);
		queryWrapper.le("indicator_date", endDate);
		
		TIndicatorsEntity one = this.getOne(queryWrapper);
		if(one != null) {
			return one.getSumIndicatorValue().setScale(4,BigDecimal.ROUND_HALF_UP);
		}
    	return new BigDecimal(0);
    	
    };
    
    //查询工具 -- 查询昨天的数据 阈值 是否超限
    public TIndicatorsEntity selectYesterDay(String startDate,String endDate,String code){
		QueryWrapper<TIndicatorsEntity> queryWrapper = new QueryWrapper<TIndicatorsEntity>();
		queryWrapper.eq("indicator_code", code);
		queryWrapper.ge("indicator_date", startDate);
		queryWrapper.le("indicator_date", endDate);
		TIndicatorsEntity one = this.getOne(queryWrapper);
    	return one;
    	
    };
    
    //计算（昨天-前天）/前天
    public BigDecimal floatDay(BigDecimal t1,BigDecimal t2) {
    	BigDecimal subtract = t1.subtract(t2);
    	BigDecimal divide = subtract.divide(t2).setScale(4,BigDecimal.ROUND_HALF_UP);
		return divide;
    	
    }
    //通用方法
    public List<ExcelBean> generalCode(String DateTime,String code) {
    	//如果 DateTime 不等于空 查询DateTime前八天的   等于空查询当前系统时间前八天的
		//查询前8天的金额
        ConcurrentHashMap<String, String> concurrentHashMap = null;
		try {
			concurrentHashMap = DateUtil.getInTheTirstDaysDate(DateTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//查询昨天的数据 阈值 是否超限
		TIndicatorsEntity selectYesterDay = this.selectYesterDay(concurrentHashMap.get("startT1"), concurrentHashMap.get("endT1"),code);
        //前1天的金额
		BigDecimal  day1=  this.selectIndexEachDay( concurrentHashMap.get("startT1"), concurrentHashMap.get("endT1"),code);
		//前2天的金额
		BigDecimal  day2=  this.selectIndexEachDay( concurrentHashMap.get("startT2"), concurrentHashMap.get("endT2"),code);
		//.....
		BigDecimal  day3=  this.selectIndexEachDay( concurrentHashMap.get("startT3"), concurrentHashMap.get("endT3"),code);
		BigDecimal  day4=  this.selectIndexEachDay( concurrentHashMap.get("startT4"), concurrentHashMap.get("endT4"),code);
		BigDecimal  day5=  this.selectIndexEachDay( concurrentHashMap.get("startT5"), concurrentHashMap.get("endT5"),code);
		BigDecimal  day6=  this.selectIndexEachDay( concurrentHashMap.get("startT6"), concurrentHashMap.get("endT6"),code);
		BigDecimal  day7=  this.selectIndexEachDay( concurrentHashMap.get("startT7"), concurrentHashMap.get("endT7"),code);
		BigDecimal  day8=  this.selectIndexEachDay( concurrentHashMap.get("startT8"), concurrentHashMap.get("endT8"),code);

		
		ArrayList<ExcelBean> List = new ArrayList<ExcelBean>();
		ExcelBean excelBean = new ExcelBean();
		excelBean.setT1(day1.toString());
		excelBean.setT2(day2.toString());
		excelBean.setT3(day3.toString());
		excelBean.setT4(day4.toString());
		excelBean.setT5(day5.toString());
		excelBean.setT6(day6.toString());
		excelBean.setT7(day7.toString());
		excelBean.setT8(day8.toString());
		//计算浮动  （昨天-前天）/前天
		//String day = "day";
		BigDecimal floatDay = new BigDecimal(0);
		if(day1.compareTo(BigDecimal.ZERO) == 0) {
			excelBean.setFalotRate("0");
    	}else {
    		if(day2.compareTo(BigDecimal.ZERO)!=0) {
    			 floatDay = floatDay(day1,day2);
    		}else {
    			if(day3.compareTo(BigDecimal.ZERO)!=0) {
    				 floatDay = floatDay(day1,day3);
    			}else {
    				if(day4.compareTo(BigDecimal.ZERO)!=0) {
        				 floatDay = floatDay(day1,day4);
        			}else {
        				if(day5.compareTo(BigDecimal.ZERO)!=0) {
            				 floatDay = floatDay(day1,day5);
            			}else {
            				if(day6.compareTo(BigDecimal.ZERO)!=0) {
                				 floatDay = floatDay(day1,day6);
                			}else {
                				if(day7.compareTo(BigDecimal.ZERO)!=0) {
                    				 floatDay = floatDay(day1,day7);
                    			}else {
                    				if(day8.compareTo(BigDecimal.ZERO)!=0) {
                        				 floatDay = floatDay(day1,day8);
                            			
                        			}
                    			}
                			}
            			}
        			}
    			}
    		}
    	}
		excelBean.setFalotRate(floatDay.toString());
		//阈值
		TThresholdEntity one = tThresholdService.getOneTThreshold(code);
		if(one != null) {
			String setThresholdValue = ThresholdUtlis.setThresholdValue(one.getThresholdValue());
			excelBean.setThresholdValue( setThresholdValue);
			
			//根据浮动判断是否超限
			String thresholdValue = one.getThresholdValue();
			Expression exp =  AviatorEvaluator.compile(thresholdValue);
			Map<String,Object> map1 = new HashMap<String,Object>();
			map1.put("Value",floatDay);
			Boolean bool = (Boolean) exp.execute(map1);
			
			excelBean.setIsOverLimit("未超限");
			if(bool) {
				excelBean.setIsOverLimit("已超限");
			}
			
		}
		
		List.add(excelBean);
		
		
		return List;
    	
    }
    
	//非货币积分发放金额浮动比率
	@Override
	public List<ExcelBean> getJFS_M001(String DateTime) {
		//String code ="JFS_M001";
		return this.generalCode(DateTime,"JFS_M001");
	}

	 // 非人民币货币积分发放金额浮动比率
	@Override
	public List<ExcelBean> getJFS_M002(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFS_M002");
	}

	// 事后结算积分发放金额浮动比率
	@Override
	public List<ExcelBean> getJFS_M003(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFS_M003");
	}

	// 单用户货币积分余额> N浮动比率
	@Override
	public List<ExcelBean> getJFS_M004(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFS_M004");
	}

	// 单用户非货币积分余额> N浮动比率
	@Override
	public List<ExcelBean> getJFS_M005(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFS_M005");
	}

	// 临时用户（非注册用户,即不使用userID用户）交易数量浮动比		
	@Override
	public List<ExcelBean> getJFS_M006(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFS_M006");
	}

	// 积分余额为负数量	
	@Override
	public List<ExcelBean> getJFS_M007(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFS_M007");
	}

	//外部积分（转接/兑换）承兑金额浮动告警
	@Override
	public List<ExcelBean> getJFU_M001(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFU_M001");
	}

	//各积分类别消费中各支付产品类型笔数占比浮动
	@Override
	public List<ExcelBean> getJFU_M002(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFU_M002");
	}

	//各积分类别消费中各支付产品类型金额占比浮动
	@Override
	public List<ExcelBean> getJFU_M003(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFU_M003");
	}

	//积分撤销/冲正/退货反向交易笔数占比浮动
	@Override
	public List<ExcelBean> getJFU_M004(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFU_M004");
	}

	//积分撤销/冲正/退货反向交易金额占比浮动
	@Override
	public List<ExcelBean> getJFU_M005(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFU_M005");
	}

	//营销系统系统成功率
	@Override
	public List<ExcelBean> getJFU_M006(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFU_M006");
	}

	//积分兑换价值比不为1笔数
	@Override
	public List<ExcelBean> getJFU_M007(String DateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(DateTime,"JFU_M007");
	}

	//已失效积分金额浮动比率
	@Override
	public List<ExcelBean> getJFU_M008(String dateTime) {
		// TODO Auto-generated method stub
		return this.generalCode(dateTime,"JFU_M008");
	}
	
	public TIndicatorsEntity setTIndicatorsEntity(TIndicatorsEntity tIndicatorsEntity) {
		//积分送分
		TThresholdEntity one = tThresholdService.getOneTThreshold(tIndicatorsEntity.getIndicatorCode());
		if(one != null) {
			tIndicatorsEntity.setCreatTime(new Date());
			tIndicatorsEntity.setSysCode(one.getSysCode());
			tIndicatorsEntity.setSysName(one.getSysName());
			tIndicatorsEntity.setIndicatorCode(one.getIndicatorCode());
			tIndicatorsEntity.setIndicatorName(one.getIndicatorName());
			try {
				tIndicatorsEntity.setIndicatorDate(DateUtil.getYestodayDate());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	//		String thresholdValue = one.getThresholdValue();
	//		Expression exp =  AviatorEvaluator.compile(thresholdValue);
	//		Map<String,Object> map1 = new HashMap<String,Object>();
	//		map1.put("Value",new BigDecimal(tIndicatorsEntity.getIndicatorValue()));
	//		Boolean bool = (Boolean) exp.execute(map1);
	//		//System.out.println(bool);//true/false
	//		if(bool) {
				//未超限
	//			tIndicatorsEntity.setIsOverLimit("1");
	//		}else {
	//			tIndicatorsEntity.setIsOverLimit("0");
	//		}
		}
		
		return tIndicatorsEntity;
		
		
	}
    @Override
	public TIndicatorsEntity getTIndicatorsOne(QueryWrapper<TIndicatorsEntity> queryWrapper) {
		// TODO Auto-generated method stub
		return this.getOne(queryWrapper);
	}
    
  //删除当天的指标
  	private void deleteTIndicatorsEntity(TIndicatorsEntity tIndicatorsEntity) {
  		QueryWrapper<TIndicatorsEntity> queryWrapper = new QueryWrapper<TIndicatorsEntity>();
		queryWrapper.eq("indicator_code", tIndicatorsEntity.getIndicatorCode());
  		queryWrapper.ge("creat_time", DateUtil.getDayFirstSecond(new Date()));
  		queryWrapper.le("creat_time", DateUtil.getDayLastSecond(new Date()));
  		this.remove(queryWrapper);
  	}
}
